// 创建团队，开账号
const cloud = require('wx-server-sdk');
const moment = require('moment');
const DEFAULT_APPID = "wx53f453674085a5ce";
const DEFAULT_BUCKET = "p-1301301505";
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
  throwOnNotFound: false
})
const db = cloud.database();
const _ = db.command;

buildQr = async (id) => {
  await cloud.callFunction({
    name: 'buildStudioQr',
    data: {
      id: id
    },
    success: res => {
      console.log(res);
      return res
     
      
    }
  })
}

// 创建团队，开账号
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  console.log(event.studio);
  // let user = event.user;
  let studio = event.studio;
  studio._openid = wxContext.OPENID;
  studio.createtime = moment().format();
  studio.visit = 0;
  studio.theme = {
    fontColor: "#ffffff",
    mainColor: "#C2B27F",
    portfolio_layout: 0,
    service_layout: 0,
    template: 0
  }
  //默认值
  studio.logo = studio.logo || {
    src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/defaultlogo.png'
  }
  studio.slogan = studio.slogan || '[示例]留住美好瞬间'
  studio.nodes = studio.nodes || '<p>[示例]一直致力于学习孩子的简单 记录孩子的成长，每一张作品都是对童年的记录，温馨家庭生活的阐释，置身作品之外，却仿佛身在情境之中</p>'
  studio.cover = {
    height: 75,
    list: [{
        src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/4.jpg'
      },
      {
        src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/3.jpg'
      },
      {
        src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/6.jpg'
      }
    ]
  }
  studio._id = wxContext.OPENID;
  if (studio.serviceType == undefined) {
    studio.serviceType = '共享版';
    studio.cos = 50;
    studio.appid = DEFAULT_APPID;
    studio.bucket = DEFAULT_BUCKET;
    studio.expireDate = moment().add(3, 'month').format("YYYY-MM-DD"); // 三个月体验期
  }
  studio.qr=`https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/userAsset/${studio._id}/qr.jpg`
 //studio.qr = `https://${DEFAULT_BUCKET}.file.myqcloud.com/${studio._id}/qr.jpg`
  // let studioCount = (await db.collection('studio').where({_openid: wxContext.OPENID, serviceType: '体验版'}).count());
  // console.log(studioCount)
  // if (studioCount.total >= 1){ // 系统限制，是否有必要？
  //   throw new Error("您最多可以创建一个体验版工作室，请联系客服");
  // }


  const transaction = await db.startTransaction();
  try {
    let studio_res = await transaction.collection('studio').add({
      data: studio
    });
    console.log(studio_res);
    // studio._id = studio_res._id;
    let team_user = {
      _openid: wxContext.OPENID,
      createtime: moment().format(),
      openid: wxContext.OPENID,
      phone: studio.create.phone,
      status: 1,
      sales: 0,
      studioid: studio._id,
      name: studio.title,
      job: '管理员'
    }
    if (event.user) {
      team_user.nickName = event.user.nickName;
      team_user.avatarUrl = event.user.avatarUrl;
    }
    let team_res = await transaction.collection('team').add({
      data: team_user
    });
    console.log(team_res);
    let service = {
      studioid: studio._id,
      _openid: wxContext.OPENID,
      createtime: moment().format(),
      cover: {
        src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/3.jpg'
      },
      title: '[示例]新年全家福',
      desc: '新年喜庆、温暖感恩',
      category: '家庭',
      price: 1500,
      deposit: 500,
      film: 50,
      album: 10,
      coupon: {
        price: 35,
        couponType: 0,
        amount: 10,
        bonus: 2,
        desc: '加片35元/张'
      },
      fixCoupon: {
        price: 50,
        couponType: 0,
        amount: 10,
        bonus: 2,
        desc: '加片50元/张'
      },
      nodes: '<p>这里放一些套系说明</p>',
      samples: [{
          src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/4.jpg'
        },
        {
          src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/3.jpg'
        },
        {
          src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/6.jpg'
        }
      ],
      status:1
      // hours: 2,
      // clothes: 0,
      // scene: 1,
      // filmGive: true,
      // albumGive: true,
    }
    let portfolio = {
      studioid: studio._id,
      _openid: wxContext.OPENID,
      createtime: moment().format(),
      cover: {
        src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/6.jpg'
      },
      title: '[示例]新年全家福',
      category: '家庭',
      nodes: '<p>这里放一些作品介绍</p>',
      samples: [{
          src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/3.jpg'
        },
        {
          src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/4.jpg'
        },
        {
          src: 'https://6561-easyphoto-7gvh0dv16ef2d12c-1304274854.tcb.qcloud.la/defaultData/6.jpg'
        }
      ]
    }
    let service_res = await transaction.collection('service').add({
      data: service
    });
    let portfolio_res = await transaction.collection('portfolio').add({
      data: portfolio
    });
    console.log(service_res);
    console.log(portfolio_res);
    // console.log(studio);
    await buildQr(studio._id);
    await transaction.collection('user').doc(wxContext.OPENID).update({
      data: {
        studioid: studio._id
      }
    });
    transaction.commit();
    // await transaction.collection('studio').doc(studio._id).update({data: {qr: }});
    // 更新用户表
    // user.studio = studio;
    // user.studioid = studio._id;
    return {
      success: true,
      studio: studio
    }
  } catch (e) {
    // if (studio._id){
    //   await db.collection('studio').doc(studio._id).remove()
    // }
    transaction.rollback();
    console.error(e);
    return {
      success: false,
      errMsg: e
    }
  }
}